<?php
// +----------------------------------------------------------------------
// | 杭州十禾信息科技有限公司
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2015 http://www.shelpe.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: LeePuman <ysyzlsm@163.com>
// +----------------------------------------------------------------------

class AdminAction extends NewzanAction
{
    public function _initialize()
    {
        if(ACTION_NAME == 'login') {

        } else if(!session('admin') && __ACTION__ != '/Admin/login') {
            $this->error("权限不足");
        } else {
            parent::_initialize();
        }
    }
    
    public function auth()
    {
        $user_id = $this->_get('user_id');
        $adgroup_id = $this->_get('adgroup_id');
        $version = $this->_get('version');
        $userMdl = new UserModel();
        if(!$user_id && $adgroup_id) {
            //find user_id and login
            $adgroupMdl = new AdgroupModel();
            $whr = array( 'adgroup_id' => $adgroup_id );
            $adgroup = $adgroupMdl->where($whr)->find();
            if(empty($adgroup)){
                throw new NewzanException('找不到该推广组，无法登陆此用户' , RetStatus::LOGIC_ERR);
            }
            $user_id = $adgroup['user_id'];
        }
        //auth user
        // $whr = array( 'user_id' => $user_id );
        $user = $userMdl->getUserByTaobaoId($user_id);
        if(empty($user)) {
            throw new NewzanException('找不到该用户' , RetStatus::LOGIC_ERR);
        }
        
        //check if need manager
        $taobao_user_id = $user['user_id'];
        $oauth = D('oauth')->where( 'taobao_user_id = ' . $taobao_user_id )->find();
        if(empty($oauth))
            throw new NewzanException('找不到该用户oauth授权' , RetStatus::LOGIC_ERR);
        $user['oauth'] = $oauth;
		
        if($user['authorized_users']) {
            session('me' , $user);
            if(!empty($user['authorized_users'])) { // 存在授权用户, 进去授权页面去更新授权用户
                session('manager' , $user);
                redirect('/user/authusers?forcefresh=1');
            } else {
                session('manager' , $user);
            }
        } else {
            $manager = $userMdl->where( 'user_id = ' . $taobao_user_id)->find();
            $manager['oauth'] = $oauth;
            session('manager' , $manager);
            if(!empty($manager['authorized_users'])) {
                $manager['authorized_users'] = explode(',' , $manager['authorized_users'] );
            }
            session('me' , $user);
        }

        require_once LIB_PATH . "Library/TaobaoAPI/Curl.php";
        R('Home/User/getAccountToken', array('user_id'=>$user['user_id'], 'http' => new Curl()));
        R('Home/Index/userLoginrecord', array('source'=>'admin'));

        //redirect
        if($adgroup_id) {
            redirect( '/adgroup/manage?adgroup_id=' . $adgroup_id );
        } else {
            redirect('/');
        }
    }
    
    public function member()
    {
        $page = $this->_post('page');
        $nick = $this->_post('nick');
        $order = $this->_post('sort');
        $desc = $this->_post('desc');
        $size = $this->_post('size');
        $keyword = $this->_post('keyword');
        $tag = $this->_post('tag');
        $from = $this->_post('from');
        $to = $this->_post('to');
        $filter = $this->_post('filter');
        $from = $from ? $from : date('Y-m-d' , strtotime("-8 day") );
        $to = $to ? $to : date('Y-m-d' , strtotime("-1 day") );
        $page = $page ? $page : 1;
        $order = $order ? $order : 'sales';
        $desc = $desc == 'asc' ? $desc : 'desc';
        $size = $size ? $size : 20;
        
        if( $keyword ){
            $filter = array( 'keyword' => $keyword );
        }

        
        if( $this->isAjax() ){
            $userMdl = D('User');
            $whr = array();
            $adminMdl = new AdminModel();
            $users = $adminMdl->getCustomers( $page , $limit ,$order , $desc , $filter , $tag);     
            $user_ids = array_column($users , 'user_id');

            if(!empty($user_ids)){
                $whr['user_id'] = array('IN' , $user_ids);
                $contacts = M('user_info')->where($whr)->select( array('assoc_key' => true) );
            }
            $ztc_versions = C('ZTC_ROLES');
            $adgroupMdl = new AdgroupModel();
            foreach( $users as &$user){
                $user['cost'] = $user['cost']/100;
                $user['cpc'] = $user['cpc']/100;
                $user['sales'] = (doubleval($user['indirect_pay'])+doubleval($user['direct_pay']))/100;
                if( empty($user['item_code']) ){
                    $item_code = $user['manager']['item_code'];
                }else{
                    $item_code = $user['item_code'];
                }
                $user['item_code'] = $item_code;
                if( isset($ztc_versions[$item_code])  ){
                    $user['item_code'] = $ztc_versions[$item_code]['name'];
                }else{
                    $user['item_code'] = '未知版本';
                }

            }
            $users = empty( $users ) ? array() : $users;
        	$this->display_json( $users );
        }else{
            //$this->tags = D('user_tags')->where('num > 0')->order('num desc')->select();
            $this->groups = $groups;
        	$this->loadJS("template",'date' , 'daterangepicker', 'jquery.tagsinput');
        	$this->display();
        }
    }
    
    // 关闭现有登录入口
    public function login()
    {
        if($this->isPost()){
            $nick = $this->_post('nick');
            $password = $this->_post('password');
            $whr = array(
                'admin' => $nick,
                'password' => md5($password)
            );
            $admin = M('admin')->where($whr)->find();
            if($admin){
                // login to 妞妞猪猪516 as default user
                session('me' , "管理员登录");
                session('admin' , $admin);
                $result = true;
                $info = '登陆成功，正在跳转中...';
            } else {
                $result = false;
                $info = '帐号或者密码不对';
            }
            $res = array(
                'result' => $result,
                'info' => $info
            );
            $this->display_json( $res );
        } else {
            $admin = $this->_get('admin');
            $ret = in_array(strtolower($admin), array('kungu', 'longkui')) ? true : false;
            if(!$ret){
                redirect('/404');
            }
            $this->admin = $admin;
            $this->display();
        }
    }

    public function mark()
    {
        $action = $this->_post('action'); 
        switch($action){
        
            case 'tag' : 
                $tag = $this->_post('tag');
                $uid = $this->_post('uid');
                $whr = 'user_id='.$uid;
                $user = D( 'customers' )->where($whr)->find();
                if( $user ){
                    $tags = explode( ',' , $user['tags']); 
                    $ix = array_search( $tag , $tags); 
                    if( $ix === false ){
                        $tags[] = $tag; 
                        //add tag or update tag
                    }else{
                        unset( $tags[$ix] );    
                    }
                    $tags = implode(',' , $tags);
                    D('customers')->where($whr)->save( array('tags' => $tags)) ; 
                    $has = D('user_tags')->where( array('tag'=> $tag) )->find();
                    if( !$has ){
                        D('user_tags')->add( array( 'num' => 1 , 'tag' => $tag , 'created_time' => date('Y-m-d H:i:s') ) ); 
                    }else{
                        if( $ix === false ){
                            $num = $has['num'] + 1; 
                        }else{
                            $num = $has['num'] - 1; 
                        }
                        D('user_tags')->where( 'tag_id = ' . $has['tag_id'] )->save( array('num' => $num) ); 
                    }
                } 
            break;


            case 'note':
                $text = $this->_post('text');
                $uid = $this->_post('uid');
                $whr = 'user_id='.$uid;
                D('customers')->where($whr)->save( array('note' => $text)) ; 
            break;
        
        }
    }
}
